<template>
  <div class="slider" ref="slider">
    <div class="slider-group" ref="sliderGroup">
      <slot></slot>
    </div>
    <div class="dots">
      <span class="dot" :class="{active: currentPageIndex === index }" v-for="(item, index) in dots"></span>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import {addClass} from "../../common/js/dom";
  import BScroll from 'better-scroll'

  export default {
    name: 'slider',
    props: {
      loop: { // 是否循环播放
        type: Boolean,
        default: true
      },
      autoPlay: { // 自动播放
        type: Boolean,
        default: true
      },
      interval: { // 自动轮播间隔
        type: Number,
        default: 4000
      }
    },
    data () {
      return {
        dots: [],
        currentPageIndex: 0
      }
    },
    mounted () {
      setTimeout(() => {
        this._setSliderWidth()
        this._initDots()
        this._initSlider()

        if (this.autoPlay) {
          this._play()
        }
      }, 20)

      window.addEventListener('resize', () => {
        if (!this.slider) {
          return
        }
        this._setSliderWidth(true)
        this.slider.refresh()
      })
    },
    activated () {
      if (this.autoPlay) {
        this._play()
      }
    },
    deactivated () {
      clearTimeout(this.timer)
    },
    beforeDestroy () {
      clearTimeout(this.timer)
    },
    methods: {
      // 因为是横向滚动，需计算slide 的宽度并且赋值
      _setSliderWidth (isResize) {
        this.children = this.$refs.sliderGroup.children  // 获取整个列表有多少个元素

        let width = 0 // 总的宽度
        let sliderWidth = this.$refs.slider.clientWidth // slide 父元素的宽度
        for (let i = 0; i < this.children.length; i++) {
          let child = this.children[i] // 获取每个子元素
          addClass(child, 'slider-item') // 添加名为slider-item的类名

          child.style.width = sliderWidth + 'px'
          width += sliderWidth
        }
        if (this.loop && !isResize) { // 如果slide是需要循环的话，slide会在左右两侧copy两个子元素从而保证循环切换
          width += 2 * sliderWidth
        }
        this.$refs.sliderGroup.style.width = width + 'px'
      },
      _initSlider () { // 初始化slide
        this.slider = new BScroll(this.$refs.slider, {
          scrollX: true,  // 横向滚动
          scrollY: false, // 不允许纵向滚动
          momentum: false,// 是否开启动量动画，关闭可以提升效率
          // ***配置:在better-scroll版本0.1.15以前可用以下参数进行slide配置，但1.0.0版本以上需按照未注释前的方法使用***/
          // snap: true, // slide组件
          // snapLoop: this.loop, // 循环
          // snapThreshold: 0.3, //
          // snapSpeed: 400
          snap: true,
          snapLoop: true,
          snapThreshold: 0.3,
          snapSpeed: 400
        })

        this.slider.on('scrollEnd', () => {
          // 参考文档 https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/api-specific.html#getcurrentpage
          let pageIndex = this.slider.getCurrentPage().pageX
          if (this.loop) {
            pageIndex -= 1 // 因为设置自动播放之后，会自动在左右两侧copy两个子元素，所以在设置pageIndex时应减一
          }
          this.currentPageIndex = pageIndex

          if (this.autoPlay) {
            this._play()
          }
        })

        this.slider.on('beforeScrollStart', () => {
          // 参考文档 https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/events.html#beforescrollstart
          if (this.autoPlay) {
            clearTimeout(this.timer)
          }
        })
      },
      _initDots () {
        this.dots = new Array(this.children.length)
      },
      _play () {
        let pageIndex = this.currentPageIndex + 1
        if (this.loop) {
          pageIndex += 1
        }
        this.timer = setTimeout(() => {
          this.slider.goToPage(pageIndex, 0, 400)
        }, this.interval)
      }
    }
  }
</script>

<style lang="scss">
  .slider{
    min-height: 1px;
    .slider-group{
      position: relative;
      overflow: hidden;
      white-space: nowrap;
      .slider-item{
        float: left;
        box-sizing: border-box;
        overflow: hidden;
        text-align: center;
        /*height: 155px;*/
        a{
          position: relative;
          display: block;
          width: 100%;
          padding-bottom: 50%;
          overflow: hidden;
          text-decoration: none;
          img{
            display: block;
            width: 100%;
            height: 100%;
          }
        }
      }
    }
    .dots{
      position: absolute;
      right: 0;
      left: 0;
      bottom: 20px;
      text-align: center;
      font-size: 0;
      .dot{
        display: inline-block;
        margin: 0 4px;/*rem*/
        width: 8px;/*rem*/
        height: 8px;/*rem*/
        border-radius: 50%;
        background: rgba(255, 255, 255, 0.5);
      }
      .active{
        width: 20px;/*rem*/
        border-radius: 5px;/*rem*/
        background: rgba(0, 122, 255, 1);
      }
    }
  }
</style>
